package cz.myslivec.slovicka.vocimport;

import java.io.IOException;
import java.io.Serializable;
import java.util.Arrays;

import javax.persistence.EntityManager;
import java.io.InputStream;

import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.log.Log;

import cz.myslivec.slovicka.entity.Lesson;
import cz.myslivec.slovicka.entity.Vocable;
import cz.myslivec.slovicka.entity.VocableType;
import cz.myslivec.slovicka.vocimport.csvparse.VocableParser;

import org.jboss.seam.international.StatusMessage;
import org.jboss.seam.international.StatusMessages;

@Name("testImport001")
@AutoCreate
public class TestImport001 implements Serializable {
	private static final long serialVersionUID = -7941251106196201805L;

	@Logger
	private Log log;
	
	@In
	private EntityManager entityManager;
	
	@In
	VocableParser vocableParser;
	
	private InputStream uploadedData;
	
	public void execute() {
		
	}
	
	public void pom01() {
		// VOCABLE TYPE
		VocableType vocType = new VocableType();
		vocType.setCode("AJ/CJ");
		vocType.setDescription("cesko anglicka slovicka");
		vocType.setStr1("anglicky");
		vocType.setStr2("cesky");
		entityManager.persist(vocType);

		// LESSON
		Lesson lesson = new Lesson();
		lesson.setName("lekce 1");
		lesson.setNote("lekce 1 - poznamka");
		lesson.setVocType(vocType);
		entityManager.persist(lesson);
		
		Lesson lesson2 = new Lesson();
		lesson2.setName("lekce 2");
		lesson2.setNote("lekce 2 - poznamka");
		lesson.setVocType(vocType);
		entityManager.persist(lesson2);
		
		// VOCABLE
		Vocable vocable1 = new Vocable();
		vocable1.setStr1("hello");
		vocable1.setStr2("ahoj");
		entityManager.persist(vocable1);
		vocable1.setLessons(Arrays.asList(lesson));
		lesson.addVocable(vocable1);

		entityManager.flush();
	}
	
	//-----

	public void parse() {
		log.info("<><><>");
		try {
			if (uploadedData != null) {
				vocableParser.parseInputStream(uploadedData);
			} else {
				StatusMessages.instance().addFromResourceBundle(StatusMessage.Severity.ERROR, "menu-setup.initial-load.xhtml.error.file_not_provided");
			}
		} catch (IOException e) {
			StatusMessages.instance().addFromResourceBundle(StatusMessage.Severity.ERROR, "menu-setup.initial-load.xhtml.error.parsing");
			log.error("Can not parse data",e);
		}
	}

	public InputStream getUploadedData() {
		return uploadedData;
	}

	public void setUploadedData(InputStream uploadedData) {
		this.uploadedData = uploadedData;
	}
}
